#include <ctype.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "util.h"
#include "json.h"

struct pos {
	char lat[16];
	char lon[16];
};

static struct pos pos;

void
processnode(struct json_node *nodes, size_t depth, const char *value)
{
	if (depth != 7 ||
	    nodes[4].type != JSON_TYPE_ARRAY ||
	    nodes[5].type != JSON_TYPE_ARRAY ||
	    strcmp(nodes[4].name, "coordinates") != 0)
		return;

	switch (nodes[5].index) {
	case 0:
		switch (nodes[4].index) {
		case 0:
			memset(&pos, 0, sizeof(pos));
			break;
		default:
			printf("%s,%s", pos.lat, pos.lon);
			break;
		}
		strlcpy(pos.lon, value, sizeof(pos.lon));
		break;
	case 1:
		strlcpy(pos.lat, value, sizeof(pos.lat));
		switch (nodes[4].index) {
		case 0:
			// do nothing
			break;
		default:
			printf(" %s,%s\n", pos.lat, pos.lon);
			break;
		}
		break;
	}
}

int
main(void)
{
	switch (parsejson(processnode)) {
	case JSON_ERROR_MEM:
		fputs("error: cannot allocate enough memory\n", stderr);
		return 2;
	case JSON_ERROR_INVALID:
		fputs("error: invalid JSON\n", stderr);
		return 1;
	}

	return 0;
}
